import React, { useState } from 'react';
import { Button, Input } from 'antd';
import { connect, formatMessage, history } from 'umi';
import { SelectLang, DrawerForm, Form } from '@/zero';
import { validatePassword } from '@/utils/default';
import LoginForm from '../_components/LoginForm';
import styles from './index.less';

const mapStateToProps = ({ loading }) => ({
  loadingGlobal: loading.global,
});

const mapDispatchToProps = (dispatch) => ({
  userLogin: (payload) =>
    dispatch({
      type: `global/userLogin`,
      payload,
    }),
  resetPassword: (payload) =>
    dispatch({
      type: `global/resetPassword`,
      payload,
    }),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)((props) => {
  const { userLogin, resetPassword, loadingGlobal } = props;

  const [errorMessage, setErrorMessage] = useState('');

  const [currentUser, setCurrentUser] = useState({});

  const onSubmit = (newRecord) => {
    userLogin(newRecord).then((response) => {
      if (response.success) {
        const { firstLogin, isPasswordExpire } = response.data;
        const newPasswordExpired = !!firstLogin || !!isPasswordExpire;
        if (newPasswordExpired) {
          setCurrentUser({
            ...response.data,
            newPasswordExpired,
          });
        } else {
          history.push('/');
        }
      } else {
        setErrorMessage(response.data.message);
      }
    });
  };

  return (
    <div className={styles.container}>
      <div className={styles.rowContainer}>
        <div className={styles.columnContainer}>
          <p
            style={{
              color: 'white',
              fontWeight: 'normal',
              fontSize: '60px',
              lineHeight: '60px',
              marginBottom: '36px',
            }}
          >
            {formatMessage({ id: 'project.long-name' })}
          </p>
          <p
            style={{
              color: '#A4A4A4',
              fontSize: '18px',
              fontFamily: 'PingFang SC',
              marginBottom: '36px',
            }}
          >
            Now, I am your drug safety guardian!
          </p>
          <DrawerForm
            width={960}
            closable={false}
            footer={null}
            title={null}
            items={[
              {
                child: (
                  <>
                    <div className={styles.content}>
                      <div className={styles.top}>
                        <div className={styles.header}>
                          <span className={styles.title}>
                            {formatMessage({ id: 'project.long-name' })}
                          </span>
                        </div>

                        <p
                          style={{
                            fontFamily: 'PingFangSC-Regular',
                            fontSize: '24px',
                            color: '#888B8D',
                            textAlign: 'center',
                            lineHeight: '30px',
                            marginBottom: '25px',
                          }}
                        >
                          &nbsp;
                        </p>
                      </div>

                      <div className={styles.main}>
                        <LoginForm
                          account={{
                            errorMessage,
                            loading: loadingGlobal,
                          }}
                          onSubmit={onSubmit}
                        />

                        {currentUser.newPasswordExpired && (
                          <DrawerForm
                            width={600}
                            title={
                              <div style={{ display: 'flex', alignItems: 'center' }}>
                                <span style={{ marginRight: '10px' }}>
                                  {formatMessage({ id: '密码已失效' })}
                                </span>
                              </div>
                            }
                            items={[
                              {
                                child: (
                                  <Form.Item shouldUpdate noStyle>
                                    {(form) => (
                                      <>
                                        <Form.Item
                                          label={formatMessage({ id: '密码' })}
                                          name="oldpwd"
                                          rules={[
                                            {
                                              required: true,
                                              message: formatMessage({
                                                id: '请输入密码',
                                              }),
                                            },
                                          ]}
                                        >
                                          <Input.Password />
                                        </Form.Item>

                                        <Form.Item
                                          label={<span>{formatMessage({ id: '新密码' })}</span>}
                                          name="newpwd"
                                          rules={[
                                            {
                                              required: true,
                                              message: formatMessage({
                                                id: '请输入新密码',
                                              }),
                                            },
                                            {
                                              validator: (rule, value, callback) => {
                                                const { result, message } = validatePassword(
                                                  value,
                                                  {
                                                    minLength: currentUser?.company?.passwordNumber,
                                                    typeKeys:
                                                      currentUser?.company?.passwordStrength?.split(
                                                        ',',
                                                      ),
                                                  },
                                                );
                                                if (result) {
                                                  callback();
                                                } else {
                                                  callback(message);
                                                }
                                              },
                                            },
                                          ]}
                                        >
                                          <Input.Password />
                                        </Form.Item>

                                        <Form.Item
                                          label={<span>{formatMessage({ id: '确认密码' })}</span>}
                                          name="rePassword"
                                          dependencies={['newpwd']}
                                          rules={[
                                            {
                                              required: true,
                                              message: formatMessage({
                                                id: '请输入确认密码',
                                              }),
                                            },
                                            {
                                              validator: (rule, value, callback) => {
                                                if (value !== form.getFieldValue('newpwd')) {
                                                  callback(
                                                    formatMessage({ id: '两次输入的密码不匹配' }),
                                                  );
                                                } else {
                                                  callback();
                                                }
                                              },
                                            },
                                          ]}
                                        >
                                          <Input.Password />
                                        </Form.Item>
                                      </>
                                    )}
                                  </Form.Item>
                                ),
                              },
                            ]}
                            visible={currentUser.newPasswordExpired}
                            closable={false}
                            cancelButtonProps={{ style: { display: 'none' } }}
                            onOk={(newRecord, success, error) => {
                              resetPassword({
                                ...currentUser,
                                ...newRecord,
                              }).then((response) => {
                                if (response.success) {
                                  success();
                                  window.location.reload();
                                } else {
                                  error(response.data?.message);
                                }
                              });
                            }}
                          />
                        )}
                      </div>
                    </div>
                  </>
                ),
              },
            ]}
          >
            <Button className={styles.loginButton}>{formatMessage({ id: '登录' })}</Button>
          </DrawerForm>
        </div>
      </div>

      <video
        height="100%"
        width="100%"
        autoPlay
        loop
        muted
        style={{ position: 'fixed', objectFit: 'cover' }}
        src="https://dip-fex-assets.dip-ai.com/translation/video/login.mp4"
      />

      <SelectLang style={{ position: 'fixed', right: 30, top: 0, zIndex: 1000, color: '#fff' }} />
    </div>
  );
});
